package auto.app.aop;

import auto.app.util.UserGetAccount;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Component
@Aspect
public class RuleValidateAspect {
    @Autowired
    private RedisTemplate redisTemplate;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();
    private final static String redisResources="resources:accountid:%s";

    @Before("@annotation(auto.app.aop.RuleValidate)")
    public void validateRule() {
        //权限认证
        //获取当前请求的uri
        HttpServletRequest request =
                ((ServletRequestAttributes) RequestContextHolder
                        .getRequestAttributes()).getRequest();
        String uri = request.getRequestURI();
//        //获取用户拥有的uri
//        @SuppressWarnings("unchecked")
//        List<String> resoruces = (List<String>)request.getSession()
//                .getAttribute("resources");
        //获取用户的id
        Integer accountId = UserGetAccount.getAccountId();
//        Integer accountid = (Integer)request.getSession().getAttribute("accountid");
        //拼接redis获取权限
        String format = String.format(redisResources, accountId);
        List<String> resoruces= (List<String>) redisTemplate.opsForValue().get(format);
        boolean b = false;
        //判定
        for(String ruri : resoruces) {
            if(antPathMatcher.match(ruri, uri)) {
                b = true;
                break;
            }
        }
        if(!b) throw new AccessDeniedException("接口未授权");

    }
}
